<template>
  <div class="home">
    <el-row :gutter="24">
      <el-col :span="12">
        <div style="height: 500px; margin-bottom: 20px" class="echart-item">
          <div id="theEchart" ref="theEchartRef"></div>
        </div>
      </el-col>
      <el-col :span="12">
        <el-col :span="24" style="padding: 0">
          <div
            class="echart-item"
            :style="{
              height: echartItemRef?.clientHeight / 2 - 10 + 'px',
              cursor: 'pointer',
            }"
          >
            <vue3-seamless-scroll v-bind="seamScroll" :list="recordList">
              <template v-slot="{ data }">
                <div class="item">
                  <div class="item-name">{{ data.name }}</div>
                  <div class="item-content">
                    <span>介绍：都很帅</span>
                    <span
                      >年收入：{{
                        data.sum == 0 ? "未知" : `${data.sum * 12}+`
                      }}</span
                    >
                  </div>
                </div>
              </template>
            </vue3-seamless-scroll>
          </div>
        </el-col>
        <el-col :span="24" style="padding: 0">
          <div
            class="echart-item"
            :style="{
              height: echartItemRef?.clientHeight / 2 - 10 + 'px',
              marginTop: '20px',
            }"
          >
            <div
              class="echart-title"
              :style="{ backgroundColor: carouselColor }"
            >
              当月{{ sortList.slice(0, 6).length }}位至尊
            </div>
            <el-carousel
              :style="{ backgroundColor: carouselColor }"
              trigger="click"
              :interval="3000"
              :height="echartItemRef?.clientHeight / 2 - 51 + 'px'"
              direction="vertical"
              :autoplay="true"
              @change="onChangeCarousel"
            >
              <el-carousel-item
                v-for="item in sortList.slice(0, 6)"
                :key="item"
              >
                <h3
                  :style="{
                    color: '#FFF',
                    lineHeight: echartItemRef?.clientHeight / 2 - 51 + 'px',
                    textAlign: 'center',
                  }"
                  text="2xl"
                  justify="center"
                >
                  {{ item.name }}
                </h3>
              </el-carousel-item>
            </el-carousel>
          </div>
        </el-col>
      </el-col>
      <el-col :span="24">
        <div style="height: 500px" class="echart-item" ref="echartItemRef">
          <div id="histogram" ref="histogramRef"></div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import { getResize } from "@/utils";
import { User } from "./config/data";
import { list } from "./config/index";
import { Vue3SeamlessScroll } from "vue3-seamless-scroll";
import randomColor from "@/utils/color";
import * as echarts from "echarts";

const echartItemRef: any = ref(); // 用于获取左侧盒子高度并计算
const theEchartRef: any = ref();
const histogramRef: any = ref();

const recordList: any = ref<User[]>(JSON.parse(JSON.stringify(list))); // 统计数据不排序
const sortList: any = ref<User[]>(JSON.parse(JSON.stringify(list))); // top数据
const copyList: any = ref<User[]>(JSON.parse(JSON.stringify(list))); // top数据，用于比较

// 滚动组件配置
const seamScroll: any = reactive({
  step: 0.5,
  hover: true,
  wheel: true,
});

// 轮播
const carouselColor = ref(randomColor());
const onChangeCarousel = () => {
  carouselColor.value = randomColor();
};

// 需要对比的属性
const comfortArr = [
  { key: "hour", status: false }, // 时薪
  { key: "sun", status: false }, // 日薪
  { key: "sum", status: false }, // 月薪
  { key: "days", status: true }, // 当月天数
  { key: "allTime", status: true }, // 总工作时间
];
// 数据计算
const onComputTime = () => {
  // 计算折线图数据
  recordList.value.forEach((v: User) => {
    if (Array.isArray(v.endDate)) {
      // (周一到周四上班时间 * 上班天数  + 周五上班时间) / 一周上班时间 = 一周上班平均值
      let average = v.endDate.reduce((prev, cur) => (prev * 4 + cur) / 5);
      v.time = (average - v.startDate - v.break).toFixed(2);
    } else {
      v.time = (v.endDate - v.startDate - v.break).toFixed(2);
    }

    v.allTime = (v.days * v.time).toFixed(2);
    v.hour = (v.sum / v.days / v.time || 0).toFixed(2);
    if (v.hour === "Infinity" || v.hour === "-Infinity") {
      v.hour = 0;
    }
    v.sun = (v.sum / v.days || 0).toFixed(2);
  });
  // 对比递增排序总数
  for (const item of comfortArr) {
    const { key, status } = item;
    comfortChange(key, status);
  }
  // top排序计算
  getCount();
};

// 群月收入总和
const total = computed(() => {
  return recordList.value.reduce((total: User, obj: User) => {
    return total + obj.sum;
  }, 0);
});
/**
 * 排序计算，根据字段计算
 * key
 * boolean：true走小于判断，false走大于判断
 */

const comfortChange = (key: string, boolean: boolean) => {
  const keys = key as keyof User;
  sortList.value.forEach((item: User, i: number) => {
    for (var j = 0; j < sortList.value.length; j++) {
      if (boolean) {
        if (item[keys] < sortList.value[j][key]) {
          item.comfort++;
        }
      } else {
        if (item[keys] > sortList.value[j][key]) {
          item.comfort++;
        }
      }
    }
  });
};
// top排序计算
const getCount = () => {
  for (let i = 0; i < sortList.value.length; i++) {
    const v = sortList.value[i];
    for (let j = 0; j < copyList.value.length; j++) {
      const { sun, sum, name, days, comfort } = copyList.value[j];
      if (v.name !== name) {
        // (工作天数 - 对方工作天数) * 日薪 + 月薪
        // 例如：多工作2日的工资 * 日薪 + 月薪 = (26 - 24) * 日薪 + 月薪
        // 进行比较，如果对方当月假期比我多2天，则补算2天工资
        /**
         * v.days：每个人当月假期
         * days：比较对方假期
         * sun：比较对方日薪
         * sum：比较对方月薪
         */
        let num = (v.days - days) * sun + sum;
        // 进行判断递增排序总数
        // 当前用户 * 0.8 大于对方月薪递增
        if (v.sum * 0.8 > num) {
          v.comfort++;
        }
        if (v.sum * 0.7 > num) {
          v.comfort += 2;
        }
        if (v.sum * 0.6 > num) {
          v.comfort += 3;
        }
        if (v.sum * 0.5 > num) {
          v.comfort += 4;
        }
        //  如果递增排序总数相等，则工资大于对方重新排序
        if (v.comfort == comfort && v.sum > sum) {
          v.comfort++;
          // let item = sortList.value[i];
          // sortList.value[i] = copyList[j];
          // copyList[j] = item;
        }
      }
    }
  }
  sortList.value.sort((x: any, y: any) => y.comfort - x.comfort);
};
// top排序图
const getTheEchart = () => {
  const myChart = echarts.init(theEchartRef.value);
  let option = {
    // backgroundColor: '#000000',
    // backgroundColor: '#1c2879',
    xAxis: {
      splitLine: {
        show: false,
      },
      axisLabel: {
        show: false,
      },
      axisTick: {
        show: false,
      },
      splitArea: { show: false },
      axisLine: {
        show: false,
      },
    },
    grid: {
      top: 40,
      bottom: 10,
      textAlign: "center",
    },
    yAxis: {
      inverse: true,
      axisLine: {
        show: false,
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        color: "#000",
        padding: [-15, 0, 35, 18],
        formatter(value: any, index: any) {
          let str = "",
            num = "TOP" + (index + 1);
          if (index === 0) {
            str = "{a| " + num + "}{title| " + value + "}";
          } else if (index === 1) {
            str = "{b| " + num + "}{title| " + value + "}";
          } else if (index === 2) {
            str = "{c| " + num + "}{title| " + value + "}";
          } else {
            str = "{d| " + num + "}{title| " + value + "}";
          }
          return str;
        },
        rich: {
          a: {
            borderColor: "#EE6F7C",
            borderWidth: 1,
            borderRadius: [0, 10, 10, 0],
            padding: [3.5, 10, 1, -13],
            backgroundColor: "rgba(238, 111, 124, 0.8)",
          },
          b: {
            borderColor: "#FFCF5F",
            borderWidth: 1,
            borderRadius: [0, 10, 10, 0],
            padding: [3.5, 10, 1, -13],
            backgroundColor: "rgba(255, 207, 95, 0.7)",
          },
          c: {
            borderColor: "#00E8FF",
            borderWidth: 1,
            borderRadius: [0, 10, 10, 0],
            padding: [3.5, 10, 1, -13],
            backgroundColor: "rgba(0, 232, 255, 0.7)",
          },
          d: {
            borderColor: "#1A90FF",
            borderWidth: 1,
            borderRadius: [0, 10, 10, 0],
            padding: [3.5, 10, 1, -13],
            backgroundColor: "rgba(26, 144, 255, 0.7)",
          },
          title: {
            padding: [0, 0, 0, 3],
          },
        },
        align: "left",
      },
      data: sortList.value.map((v: User) => v.name),
    },
    series: [
      {
        type: "pictorialBar",
        symbol: "rect",
        symbolRotate: 30,
        symbolRepeat: "fixed",
        symbolClip: true,
        symbolOffset: [0, -1.5],
        symbolSize: [2, 12],
        symbolMargin: "3",
        itemStyle: {
          color: "#000726",
        },
        label: {
          show: true,
          color: "#000",
          fontFamily: "Bebas",
          fontSize: 12,
          offset: [-9, -1.5],
          position: "right",
          formatter(params: any) {
            let result = "";
            switch (params.dataIndex) {
              case 0:
                result = "{img|}{red|￥}{index0|" + params.value + "}{unit|}";
                break;
              case 1:
                result = "{img|}{red|￥}{index1|" + params.value + "}{unit|}";
                break;
              case 2:
                result = "{img|}{red|￥}{index2|" + params.value + "}{unit|}";
                break;
              default:
                result = "{img|}{red|￥}{index3|" + params.value + "}{unit|}";
                break;
            }
            return result;
          },
          rich: {
            red: {
              color: "red",
            },
            img: {
              height: 18,
              width: 20,
              // backgroundColor: { image: arrow },这个图片自己切，这里上传不了（加了一个尾巴的形状）
            },
            unit: {
              color: "#000",
              fontSize: 11,
            },
            index0: {
              color: "#ee6f7c",
              fontFamily: "Bebas",
              padding: [-2, 2, 0, 0],
            },
            index1: {
              color: "#ffcf5f",
              fontFamily: "Bebas",
              padding: [-2, 2, 0, 0],
            },
            index2: {
              color: "#00e8ff",
              fontFamily: "Bebas",
              padding: [-2, 2, 0, 0],
            },
            index3: {
              color: "#000",
              fontFamily: "Bebas",
              padding: [-2, 2, 0, 0],
            },
          },
        },
        symbolBoundingData:
          Math.max(...sortList.value.map((item: User) => item.sum)) * 1.3,
        data: sortList.value.map((item: User) => item.sum),
        z: 2,
      },
      {
        type: "bar",
        barWidth: 10,
        data: sortList.value.map((item: User) => item.sum),
        itemStyle: {
          color: "#00F7F0",
        },
        z: 1,
      },
      {
        type: "bar",
        barGap: "-125%", // 设置外框粗细
        data: sortList.value.map(
          (items: User) =>
            Math.max(...sortList.value.map((item: User) => item.sum)) * 1.3
        ),
        barWidth: 15,
        itemStyle: {
          color: "none",
          borderColor: "rgba(64, 245, 245, 0.5)",
          border: "1px #fff",
        },
        z: 0,
      },
    ],
  };

  getResize(option, myChart);
};
// 折线图
const typeObj: any = {
  时薪: "￥",
  日薪: "￥",
  月薪: "￥",
  每日工作时长: "小时",
  当月工作时长: "小时",
  当月工作天数: "天",
};
const getHistogram = () => {
  const myChart = echarts.init(histogramRef.value);
  let option = {
    // backgroundColor: 'white',
    grid: {
      top: "20%",
      left: "5%",
      right: "5%",
      bottom: "8%",
      containLabel: true,
    },
    // 移入数据样式
    tooltip: {
      trigger: "axis",
      backgroundColor: "rgba(1, 13, 19, 0.6)",
      borderWidth: 1,
      borderColor: "#000",
      axisPointer: {
        // type: 'shadow'
        // label: {
        //   show: true,
        // },
      },
      formatter: function (params: any) {
        var str = "";
        if (params.length > 0) {
          str = params[0].name + "<br/>";
        }
        for (var i = 0; i < params.length; i++) {
          const { seriesName, value } = params[i];
          if (seriesName) {
            str += `${seriesName}：${value}${typeObj[seriesName]}<br/>`;
          }
        }
        return str;
      },
      textStyle: {
        color: "rgba(255, 255, 255, 1)",
        // fontSize: fontChart(0.24),
      },
      extraCssText: "z-index:2",
    },
    legend: {
      left: "center",
      top: 30,
      itemWidth: 15,
      itemHeight: 10,
      itemGap: 15,
      borderRadius: 4,
      textStyle: {
        color: "#000",
        fontFamily: "Alibaba PuHuiTi",
        fontSize: 14,
        fontWeight: 400,
      },
    },
    xAxis: {
      type: "category",
      data: recordList.value.map((v: User) => v.name),
      axisLine: {
        show: false,
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        show: true,
        color: "#393939", //X轴文字颜色
      },
    },
    yAxis: [
      {
        type: "value",
        name: "收入对比",
        nameGap: 30, // 表现为上下位置
        nameTextStyle: {
          padding: [0, 0, 0, -30],
          color: "#000",
          fontFamily: "Alibaba PuHuiTi",
          fontSize: 14,
          fontWeight: 600,
        },
        splitLine: {
          show: true,
          lineStyle: {
            color: "#eeeeee",
          },
        },
        axisTick: {
          show: false,
        },
        axisLine: {
          show: false,
        },
        axisLabel: {
          show: true,
          color: "#393939",
        },
      },
      {
        type: "value",
        name: "折线",
        nameTextStyle: {
          color: "#393939",
          padding: [0, 0, 0, 40], // 四个数字分别为上右下左与原位置距离
        },
        nameGap: 30, // 表现为上下位置
        position: "right",
        splitLine: {
          show: false,
        },
        axisTick: {
          show: false,
        },
        axisLine: {
          show: false,
        },
        axisLabel: {
          show: true,
          color: "#393939",
        },
        // max: 300
      },
    ],
    series: [
      {
        name: "日薪",
        type: "line",
        yAxisIndex: 1, //使用的 y 轴的 index，在单个图表实例中存在多个 y轴的时候有用
        // showAllSymbol: true, //显示所有图形。
        symbol: "circle", //标记的图形为实心圆
        symbolSize: 8, //标记的大小
        itemStyle: {
          //折线拐点标志的样式
          color: "white",
          borderWidth: "2",
          borderColor: "#5470c6",
        },
        lineStyle: {
          color: "#5470c6",
        },
        data: recordList.value.map((v: User) => v.sun),
      },
      {
        name: "时薪",
        type: "line",
        yAxisIndex: 1, //使用的 y 轴的 index，在单个图表实例中存在多个 y轴的时候有用
        showAllSymbol: true, //显示所有图形。
        symbol: "circle", //标记的图形为实心圆
        symbolSize: 8, //标记的大小
        itemStyle: {
          //折线拐点标志的样式
          color: "white",
          borderWidth: "2",
          borderColor: "#91cc75",
        },
        lineStyle: {
          color: "#91cc75",
        },
        data: recordList.value.map((v: User) => v?.hour || 0),
      },
      {
        name: "月薪",
        type: "bar",
        barWidth: 15,
        itemStyle: {
          color: "#fdcb6c",
        },
        data: recordList.value.map((v: User) => v.sum),
      },
      {
        name: "每日工作时长",
        type: "line",
        yAxisIndex: 1, //使用的 y 轴的 index，在单个图表实例中存在多个 y轴的时候有用
        showAllSymbol: true, //显示所有图形。
        symbol: "circle", //标记的图形为实心圆
        symbolSize: 8, //标记的大小
        itemStyle: {
          //折线拐点标志的样式
          color: "white",
          borderWidth: "2",
          borderColor: "#f3454b",
        },
        lineStyle: {
          color: "#f3454b",
        },
        data: recordList.value.map((v: User) => v.time),
      },
      {
        name: "当月工作时长",
        type: "line",
        yAxisIndex: 1, //使用的 y 轴的 index，在单个图表实例中存在多个 y轴的时候有用
        showAllSymbol: true, //显示所有图形。
        symbol: "circle", //标记的图形为实心圆
        symbolSize: 8, //标记的大小
        itemStyle: {
          //折线拐点标志的样式
          color: "white",
          borderWidth: "2",
          borderColor: "#000000",
        },
        lineStyle: {
          color: "#000000",
        },
        data: recordList.value.map((v: User) => v.allTime),
      },
      {
        name: "当月工作天数",
        type: "line",
        yAxisIndex: 1, //使用的 y 轴的 index，在单个图表实例中存在多个 y轴的时候有用
        showAllSymbol: true, //显示所有图形。
        symbol: "circle", //标记的图形为实心圆
        symbolSize: 8, //标记的大小
        itemStyle: {
          //折线拐点标志的样式
          color: "white",
          borderWidth: "2",
          borderColor: "#fac858",
        },
        lineStyle: {
          color: "#fac858",
        },
        data: recordList.value.map((v: User) => v.days),
      },
    ],
  };
  getResize(option, myChart);
};

onMounted(() => {
  onComputTime();
  getTheEchart();
  getHistogram();
});
</script>

<style scoped lang="scss">
$padding: 20px;

#theEchart,
#histogram {
  width: 100%;
  height: 100%;
}

.home {
  // height: calc(100% - ($padding + 20px));
  padding: $padding;
  background-color: #f7f8fa;
}
.echart-item {
  position: relative;
  overflow: hidden;
  // overflow: auto;
  // overflow-x: hidden;
  border-radius: 10px;
  background-color: #fff;
  .item {
    display: flex;
    align-items: center;
    height: 60px;
    color: #000;
    border-bottom: 1px solid #eee;
    font-size: 10px;

    .item-name {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 40px;
      height: 40px;
      border: 1px solid #ccc;
      border-radius: 50%;
      margin-left: 10px;
    }
    .item-content {
      display: flex;
      flex-direction: column;
      margin-left: 20px;
    }
  }
  .item:last-child {
    border: none;
  }
  .echart-title {
    z-index: 999;
    position: relative;
    width: 100%;
    padding: 10px 0;
    text-align: center;
    border-bottom: 1px solid #eee;
    color: #fff;
  }
}

.total {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  height: 40px;
  padding: 0 20px;
  background: #fff;
  color: red;
  font-size: 16px;
  font-weight: 700;
}
</style>
